#!/bin/sh
# BSD 3-Clause 2023 by Kevin Bloom.

AWK_PATH=./

ledger_path=${AWK_PATH}ledge.awk
balance_path=${AWK_PATH}balance.awk
final_path=${AWK_PATH}final.awk
register_path=${AWK_PATH}register.awk
reg=${AWK_PATH}reg_values.awk

command=$1
if test "$command" = ""; then
   echo "Usage: aledger command [--start start_date] [--end end_date] file"
   echo "Try \`aledger --help' for more information."
   exit 1
fi
if test "$command" = "--help"; then
  echo " "
  echo "Usage: aledger command [--start start_date] [--end end_date] file"
  echo " "
  echo "command              balance,register"
  echo "--start,--end        YYYY/MM/DD"
  echo " "
  exit 0
fi
shift

case $command in
  balance)
    # TODO: probably should try to do this more efficiently since this is sorting twice
    for a in "$@"
    do
      case $found in
        1)
          start=$a
          found=0
          continue
          ;;
        2)
          end=$a
          found=0
          continue
          ;;
      esac
      case "$a" in
        --start)
          found=1
          ;;
        --end)
          found=2
          ;;
        *)
          file=$a
          ;;
      esac
    done
    awk -v start="$start" -v end="$end" -f $balance_path $file | sort | awk -f $ledger_path | sort | awk -f $final_path
    ;;
  register)
    for a in "$@"
    do
      case $found in
        1)
          start=$a
          found=0
          continue
          ;;
        2)
          end=$a
          found=0
          continue
          ;;
      esac
      case "$a" in
        --monthly)
          type="monthly"
          ;;
        --weekly)
          type="weekly"
          ;;
        --start)
          found=1
          ;;
        --end)
          found=2
          ;;
        *)
          file=$a
          ;;
      esac
    done
    awk -v type="$type" -v start_date="$start" -v end_date="$end" -f $register_path $file | sort | awk -f $reg
    ;;
  *)
    echo "Unknown command."
    ;;
esac
